package com.kld.shop.controller.webController;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.kld.common.framework.dto.ResultMsg;
import com.kld.common.framework.global.EnumList;
import com.kld.common.util.DateUtils;
import com.kld.common.util.RegExpUtil;
import com.kld.promotion.api.*;
import com.kld.promotion.po.*;
import com.kld.shop.controller.base.BaseWebController;
import com.kld.sys.api.ISysDictService;
import com.kld.sys.po.SysDict;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

/**
 * Created by caoZ
 */
@Controller
@RequestMapping("/activity")
public class ActivityWebController extends BaseWebController {

    @Resource
    private IActivityService iActivityService;
    @Resource
    private IActItemService iActItemService;
    @Resource
    private IActLogService iActLogService;
    @Resource
    private IPrizeService iPrizeService;

    @Resource
    private IActOrderService iActOrderService;

    @Resource
    private ISysDictService iSysDictService;

    /**
     * 查询小积分换大奖的前4条或全部活动信息
     *
     * @param
     * @return
     */
    @ResponseBody()
    @RequestMapping("/getJFPrizeList")
    public ResultMsg getJFPrizeList() {

        ResultMsg msg = new ResultMsg();
        List<Prize> list;

        PageHelper.startPage(getPageNum(), getPageSize());
        list = iActivityService.getLimitJFActList(null);
        PageInfo pageInfo = new PageInfo(list);
        msg.setResult(true);
        msg.setTotal(pageInfo.getTotal());
        msg.setRows(pageInfo.getList());

        return msg;
    }

    /**
     * 奖品查询 ，查询条件 ：是否领取奖品， 最近几个月的奖品
     * num      查前几个月的数据，num就等于几
     * state    奖品状态: 0-未领取，1-已领取
     * acttype  活动类型（1月抽奖；2积分抽奖；3砸金蛋）
     *
     * @return
     */
    @ResponseBody()
    @RequestMapping("/queryPrizesByUserId")
    public ResultMsg queryPrizesByUserId(Integer num, Integer state, Integer acttype) {
        ResultMsg msg = new ResultMsg();
        HashMap<String, Object> map = new HashMap<String, Object>();
        String userID = getUserID();
        List<PrizeInfo> list = iActivityService.queryPrizesByUserId(getUserID(), num, state, acttype);//奖品数据
        Integer times = iActivityService.queryActTimesByUserID(userID);//用户剩余抽奖机会
        map.put("times", times);
        map.put("list", list);
        msg.setResult(true);
        msg.setData(map);
        return msg;
    }

    /**
     * 更新活动订单
     *
     * @param actorder
     * @return
     */
    @RequestMapping("/updateActOrder")
    @ResponseBody
    public ResultMsg updateActOrder(Actorder actorder) {
        ResultMsg rmg = new ResultMsg();
        if (actorder == null || StringUtils.isEmpty(actorder.getAddress()) || StringUtils.isEmpty(actorder.getPhone()) || StringUtils.isEmpty(actorder.getRealname())) {
            rmg.setResult(false);
            rmg.setMsg("收货人,手机号,详细地址必须填写!");
            return rmg;
        }
        if (!RegExpUtil.isPostCode(actorder.getZip())) {
            rmg.setResult(false);
            rmg.setMsg("请填写正确的邮编！");
            return rmg;
        }
        try {
            Actlog actlog = iActLogService.selectByPrimaryKey(actorder.getActlogid());
            if (actlog == null) {
                rmg.setResult(false);
                rmg.setMsg("没有发现中奖信息！");
                return rmg;
            }
            //actorder.setActid(actlog.getActid());
            // actorder.setActitemid(actlog.getActitemid());
            actorder.setCardno(actlog.getCardno());
            //actorder.setActtype(actlog.getActtype());
            //actorder.setIswon(actlog.getIswon());
            Prize prize = iPrizeService.selectByActItemID(actlog.getActitemid());
            if (prize == null) {
                rmg.setResult(false);
                rmg.setMsg("没有发现奖品信息！");
                return rmg;
            }
            actorder.setOucode(prize.getOucode());
            actorder.setState(new BigDecimal(1));
            rmg = iActOrderService.updateActOrder(actorder);
        } catch (Exception e) {
            e.printStackTrace();
            rmg.setResult(false);
            rmg.setMsg("更新活动订单失败");
        }

        return rmg;
    }

    /**
     * 首次注册登录送砸金蛋机会
     * @return
     */
    /*@RequestMapping("/insertByRegister")
    @ResponseBody()
    public ResultMsg insertByRegister(String userid){
        Map<String,Object> map=new HashMap<String, Object>();
        ResultMsg msg = new ResultMsg();
        Actlog actlog = new Actlog();
        Sys_dict dict = iSysDictService.getSysDictByAlias("GetChanceByFirstLogin");
        map.put("userid",userid);
        map.put("actid",dict.getValue());
        map.put("acttype",3);
        List<Actlog> actlogList=iActLogService.getActlogListbyUserid(map);
        if(actlogList.size()==0) {
            actlog.setActid(new BigDecimal(dict.getValue()));
            actlog.setUserid(getUserID());
            actlog.setActtype(new BigDecimal(3));
            actlog.setUsername(getUserName());
            actlog.setTimes(new BigDecimal(1));
            actlog.setCreatetime(new Date());

            int i = iActLogService.insertSelective(actlog);
            if (i > 0) {
                msg.setResult(true);
                msg.setMsg("您获得了一次砸金蛋的机会，恭喜！");
            } else {
                msg.setResult(false);
                msg.setMsg("对不起，由于系统故障，您没有获得砸金蛋的机会！");
            }
        }
        return msg;
    }*/

    /**
     * 完成积分对换送砸金蛋机会
     *
     * @return
     */
    @ResponseBody()
    @RequestMapping("/insertByCompleteExchange")
    public ResultMsg insertByCompleteExchange() {
        ResultMsg result = new ResultMsg();
        Actlog actlog = new Actlog();
        SysDict dict = iSysDictService.getSysDictByAlias("GetChanceByCompleteExchange");
        Activity act = iActivityService.selectByPrimaryKey(new BigDecimal(dict.getValue()));
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("actid", act.getId());
        map.put("userid", getUserID());
        map.put("acttype", 3);
        List<Actlog> actlogList = iActLogService.getActlogListbyUserid(map);
        if (act.getState().intValue() == 2 && actlogList.size() == 0) {
            actlog.setActid(new BigDecimal(dict.getValue()));
            actlog.setUserid(getUserID());
            actlog.setActtype(new BigDecimal(3));
            actlog.setUsername(getUserName());
            actlog.setTimes(act.getTimes());
            actlog.setCreatetime(new Date());
            int i = iActLogService.insertSelective(actlog);
            if (i > 0) {
                result.setResult(true);
                result.setMsg("您获得了砸金蛋的机会，恭喜！");
            } else {
                result.setResult(false);
                result.setMsg("对不起，由于系统故障，您没有获得砸金蛋的机会！");
            }
        } else {
            result.setResult(false);
            result.setMsg("对不起，活动已结束！");
        }
        return result;
    }

    /**
     * @param actID
     * @param cardNo
     * @return
     * @Description 小积分抽大奖
     */
    @RequestMapping("/payPointsAct")
    @ResponseBody
    public ResultMsg payPointsAct(BigDecimal actID, String cardNo) {
        ResultMsg rmg = null;
        if (org.apache.commons.lang3.StringUtils.isBlank(cardNo)) {
            rmg.setResult(false);
            rmg.setMsg("请先选择支付油卡");
            return rmg;
        }
        try {
            rmg = iActivityService.payPointsAct(actID, getUserID(), getUserName(), cardNo, EnumList.Channel.Web);
        } catch (Exception e) {
            logger.error("积分抽奖失败=============>" + e.getMessage());
            rmg = new ResultMsg();
            rmg.setResult(false);
            rmg.setMsg(e.getMessage());
            return rmg;
        }
        return rmg;
    }


    /**
     * 绑定油卡赠送砸金蛋机会
     * String userid,String username,String phone,String cardno,Date createtime
     *
     * @return
     */
    @ResponseBody()
    @RequestMapping(value = "/insertByBindCard", method = RequestMethod.POST)
    public ResultMsg insertByBindCard(BindCard bindCard) {
        logger.info("===============>门户绑定油卡送砸金蛋机会开始");
        ResultMsg msg = new ResultMsg();
        Actlog actlog = new Actlog();
        if (bindCard.getUserid() == null) {
            msg.setResult(false);
            msg.setMsg("用户id不能为空！");
            return msg;
        }
     /*   if (bindCard.getUsername() == null) {
            msg.setResult(false);
            msg.setMsg("用户名不能为空！");
            return msg;
        }
        if (bindCard.getCardno() == null) {
            msg.setResult(false);
            msg.setMsg("卡号不能为空！");
            return msg;
        }
        if (bindCard.getPhone() == null) {
            msg.setResult(false);
            msg.setMsg("手机号不能为空！");
            return msg;
        }
        if (bindCard.getCreatetime() == null) {
            msg.setResult(false);
            msg.setMsg("无绑定时间！");
            return msg;
        }*/
        bindCard.setCreatetime(DateUtils.getDate());
        try {
            logger.info("============获取砸金蛋活动Id");
            SysDict dict = iSysDictService.getSysDictByAlias("GetChanceByBindCard");
            if (dict == null || dict.getValue() == null || "".equals(dict.getValue())) {
                msg.setResult(false);
                msg.setMsg("赠送失败，未获取到绑油卡送抽奖机会系统配置字典项");
                return msg;
            }
            Activity act = iActivityService.selectByPrimaryKey(BigDecimal.valueOf(Integer.parseInt(dict.getValue().toString())));
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("actid", act.getId());
            map.put("userid", bindCard.getUserid());
            map.put("acttype", 3);
            List<Actlog> actlogs = iActLogService.getActlogListbyUserid(map);
            if (actlogs != null && actlogs.size() >= 1) {
                msg.setResult(false);
                msg.setMsg("首次绑油卡送砸金蛋机会已经用完！");
                return msg;
            } else if (act == null || act.getIsdel().intValue() == 1 || act.getType().intValue() != EnumList.ActType.GoldenEgg.value || act.getState().intValue() == EnumList.ActState.UnPublish.value) {
                msg.setResult(false);
                msg.setMsg("赠送失败，无法找到此类已发布砸金蛋活动信息");
                return msg;
            } else if (act.getState().intValue() != EnumList.ActState.Launching.value) {
                msg.setResult(false);
                if (act.getState().intValue() == EnumList.ActState.Expired.value) {
                    msg.setMsg("赠送失败，活动已结束");
                } else {
                    msg.setMsg("活动状态有误！");
                }
                return msg;
            }
            actlog.setActid(new BigDecimal(dict.getValue()));
            actlog.setUserid(bindCard.getUserid());
            actlog.setUsername(bindCard.getUsername());
            actlog.setPhone(bindCard.getPhone());
            actlog.setCardno(bindCard.getCardno());
            actlog.setCreatetime(bindCard.getCreatetime());
            actlog.setActtype(new BigDecimal(EnumList.ActType.GoldenEgg.value));
            actlog.setTimes(act.getTimes());
            int i = iActLogService.insertSelective(actlog);
            if (i > 0) {
                logger.info("============绑油卡送砸金蛋机会成功> 用户ID> " + bindCard.getUserid() + " 用户名> " + bindCard.getPhone());
                msg.setResult(true);
                msg.setMsg("您获得了" + actlog.getTimes() + "次砸金蛋的机会，恭喜！");
            } else {
                logger.error("============绑油卡送砸金蛋机会失败");
                msg.setResult(false);
                msg.setMsg("对不起，由于系统故障，您没有获得砸金蛋的机会！");
            }
        } catch (Exception ex) {
            msg.setResult(false);
            msg.setMsg("绑油卡送砸金蛋机会发生异常");
            logger.error("============绑油卡送砸金蛋机会异常> 用户ID> " + actlog.getUserid() + " 用户名> " + actlog.getPhone());
            logger.error("异常信息>>>>>>>>" + ex.toString());
        }
        return msg;
    }

    /**
     * 查询当前用户砸金蛋的机会次数
     *
     * @return
     */
    @RequestMapping("/queryActTimes")
    @ResponseBody
    public ResultMsg queryActTimes() {
        ResultMsg msg = new ResultMsg();
        HashMap<String, Object> map = new HashMap<String, Object>();
        Object cusername = getUserName();
        if (cusername == "") {
            msg.setMsg("您还未登录，请先登录！");
            msg.setResult(false);
        } else {
            Integer num = iActivityService.queryActTimesByUserID(getUserID());
            map.put("cusername", cusername);
            map.put("num", num);
            msg.setResult(true);
            msg.setData(map);
        }
        return msg;
    }

    @RequestMapping("/smashingEggs")
    @ResponseBody
    public ResultMsg smashingEggs() {
        logger.info("砸金蛋开始======================");
        ResultMsg rmg = new ResultMsg();
        String userid = getUserID();
        if (StringUtils.isBlank(userid)) {
            rmg.setResult(false);
            rmg.setMsg("请先登录");
            return rmg;
        }
        try {
            rmg = iActivityService.smashingEggs(userid, getUserName(), EnumList.Channel.Web.value);
        } catch (Exception e) {
            logger.error("砸金蛋失败,发生异常 ==> " + e.toString());
            rmg.setResult(false);
            rmg.setMsg("很抱歉，您没砸中");
        }
        logger.info("砸金蛋结束！======================");
        return rmg;
    }

    /**
     * 得到月活动奖项列表
     *
     * @return
     */
    @ResponseBody()
    @RequestMapping("/getActItemList")
    public ResultMsg GetActitmeList() {
        BigDecimal actid = null;
        List<Activity> actList_1 = iActivityService.getActListByType_1(EnumList.ActType.Monthy.value, new Date(), 1);
        if (actList_1.size() == 0) {
            List<Activity> actList_2 = iActivityService.getActListByType_1(EnumList.ActType.Monthy.value, new Date(), 2);
            if (actList_2.size() == 0) {
                List<Activity> actList_3 = iActivityService.getActListByType_1(EnumList.ActType.Monthy.value, new Date(), 3);
                if (actList_3.size() != 0) {
                    actid = actList_3.get(0).getId();
                }
            } else {
                actid = actList_2.get(0).getId();
            }
        } else {
            actid = actList_1.get(0).getId();
        }
        ResultMsg result = new ResultMsg();
        List<Actitem> list = new ArrayList<Actitem>();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("actid", actid);
        if (actid != null) {
            list = iActItemService.getActItemList(map);
        }
        result.setResult(true);
        result.setData(list);
        return result;
    }

    /**
     * 公布最近三个月的中奖名单
     *
     * @return
     */
    @ResponseBody()
    @RequestMapping("/getMonthActWinnerList")
    public ResultMsg GetMonthActWinnerList() {
        Map<String, Object> month = new HashMap<String, Object>();
        month.put("01", "一");
        month.put("02", "二");
        month.put("03", "三");
        month.put("04", "四");
        month.put("05", "五");
        month.put("06", "六");
        month.put("07", "七");
        month.put("08", "八");
        month.put("09", "九");
        month.put("10", "十");
        month.put("11", "十一");
        month.put("12", "十二");
        ResultMsg result = new ResultMsg();
        List<Activity> actList = iActivityService.getActListByEndtime(new Date());
        Map<String, Object> map = new LinkedHashMap<String, Object>();
        for (Activity act : actList) {
            Map<String,Object> pMap=new HashMap<String, Object>();
            pMap.put("actid", act.getId());
            List<Actlog> actlogList = iActLogService.getActlogListByActid(pMap);
            String key = DateUtils.formatDate( act.getStarttime(),"MM");
            map.put((String) month.get(key), actlogList);
        }
        String year = DateUtils.formatDate(DateUtils.nMonthAgo(1,new Date()),"yyyy");
        String mon = DateUtils.formatDate(DateUtils.nMonthAgo(1,new Date()),"MM");
        map.put("title", year + "年" + (String) month.get(mon) + "月");
        result.setResult(true);
        result.setData(map);
        return result;
    }

    /**
     * 根据登录用户等到电子凭证
     *
     * @return
     */
    @ResponseBody()
    @RequestMapping("/getJfActlogList")
    public ResultMsg GetJfActlogList() {
        String userid = getUserID();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("userid", userid);
        map.put("acttype", 2);
        ResultMsg result = new ResultMsg();
        PageHelper.startPage(getPageNum(), getPageSize());
        List<Actlog> list = iActLogService.getActlogListbyUserid(map);
        PageInfo pageInfo = new PageInfo(list);
        result.setResult(true);
        result.setTotal(pageInfo.getTotal());
        result.setRows(list);
        return result;
    }

    @ResponseBody()
    @RequestMapping("indexActPro")
    public ResultMsg IndexActPro(){
        ResultMsg result=new ResultMsg();
        List<Activity> actList= iActivityService.getIndexActProList(10);
        result.setResult(true);
        result.setRows(actList);
         return result;
    }
}
